package com.wave.blog.serve.controller;

import com.wave.blog.serve.common.Result;
import com.wave.blog.serve.entity.Comment;
import com.wave.blog.serve.service.CommentService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import java.util.List;

/**
 * 评论控制器
 * 提供评论相关的RESTful API接口
 *
 * @author wave
 */
@RestController
@RequestMapping("/comments")
public class CommentController {

    @Resource
    private CommentService commentService;

    /**
     * 创建评论
     *
     * @param comment 评论对象
     * @return 创建的评论对象
     */
    @PostMapping
    public Result<Comment> createComment(@RequestBody Comment comment) {
        boolean saved = commentService.addComment(comment);
        if (saved) {
            return Result.success(comment);
        }
        return Result.error("创建评论失败");
    }

    /**
     * 根据文章ID获取评论列表
     *
     * @param articleId 文章ID
     * @return 评论列表
     */
    @GetMapping("/article/{articleId}")
    public Result<List<Comment>> getCommentsByArticleId(@PathVariable Long articleId) {
        List<Comment> comments = commentService.getCommentsByArticleId(articleId);
        return Result.success(comments);
    }

    /**
     * 删除评论
     *
     * @param id 评论ID
     * @return 响应结果
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteComment(@PathVariable Long id) {
        // 检查评论是否存在
        Comment comment = commentService.getById(id);
        if (comment == null || comment.getStatus() == 2) {
            return Result.error("评论不存在或已被删除");
        }
        
        boolean deleted = commentService.deleteComment(id);
        if (deleted) {
            return Result.success();
        }
        return Result.error("删除评论失败");
    }

    /**
     * 获取所有评论列表（管理功能）
     *
     * @return 评论列表
     */
    @GetMapping("/list")
    public Result<List<Comment>> getCommentList() {
        List<Comment> comments = commentService.list();
        return Result.success(comments);
    }

    /**
     * 更新评论状态
     *
     * @param id 评论ID
     * @param status 状态值
     * @return 响应结果
     */
    @PutMapping("/{id}/status")
    public Result<Comment> updateCommentStatus(@PathVariable Long id, @RequestParam Integer status) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return Result.error("评论不存在");
        }
        
        comment.setStatus(status);
        boolean updated = commentService.updateById(comment);
        if (updated) {
            return Result.success(comment);
        }
        return Result.error("更新评论状态失败");
    }
}